package com.example.music_player

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.example.music_player.data.AppDatabase
import com.example.music_player.data.User
import kotlinx.coroutines.launch

class RegisterActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)

        val nicknameEditText = findViewById<EditText>(R.id.et_register_nickname)
        val usernameEditText = findViewById<EditText>(R.id.et_register_username)
        val passwordEditText = findViewById<EditText>(R.id.et_register_password)
        val registerButton = findViewById<Button>(R.id.btn_register_confirm)

        // 获取数据库实例
        val userDao = AppDatabase.getDatabase(this).userDao()

        registerButton.setOnClickListener {
            val nickname = nicknameEditText.text.toString().trim()
            val username = usernameEditText.text.toString().trim()
            val password = passwordEditText.text.toString().trim()

            if (nickname.isNotEmpty() && username.isNotEmpty() && password.isNotEmpty()) {
                // 在协程中插入用户数据
                lifecycleScope.launch {
                    userDao.insertUser(User(nickname = nickname, username = username, password = password))
                    Toast.makeText(this@RegisterActivity, "注册成功", Toast.LENGTH_SHORT).show()
                    finish() // 返回登录界面
                }
            } else {
                Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show()
            }

        val backToLoginButton = findViewById<Button>(R.id.btn_back_to_login)
        backToLoginButton.setOnClickListener {            // 返回登录界面
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
    }
}
}}
